import type { Position, Feature, Polygon, MultiPolygon } from '@turf/turf'
import type { ProvinceEnum, CityEnum, AreaEnum } from '~/store/global.typings'
import type {
  addOptionsPropsType,
  // xzqObj,
  assetXzqStateType,
  overlaysType,
  assetXzqDistrictListObj,
  editType
} from './typings'
import { defineComponent, onMounted, onBeforeUnmount, ref, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import {
  ElSpace,
  ElButton,
  ElPopover,
  ElTooltip,
  ElTabs,
  ElTabPane,
  ElSkeleton,
  ElDescriptions,
  ElDescriptionsItem,
  ElLink
} from 'element-plus'
import { isArray } from 'lodash'
import { polygon, multiPolygon, /* difference, */ union, area as Area } from '@turf/turf'
import AliIcon from '~/components/AliIocn' /** 阿里巴巴图标库**/
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from '../../index.module.scss'
export default defineComponent({
  name: 'MapShow',
  props: [
    'visible',
    'type',
    'record',
    'mapToolView',
    'overlaysArr',
    'cancel',
    'activeFullScreen',
    'getMapRandomPoint',
    'changeFullScreen'
  ],
  setup(props: addOptionsPropsType, { expose }) {
    const store = useStore()
    const getStoreColorData = useVuexGetters('assetWorkArea', ['color'])
    const getStoreData = useVuexGetters('assetWorkArea', ['polygonData'])
    const globalState = useVuexGetters('global', [
      'provinceSelectList',
      'citySelectList',
      'areaSelectList'
    ])

    // 定义行政区变量,省级、市级、区级
    const state = reactive<assetXzqStateType>({
      visible: true,
      activeTabKey: 'province' // 初始化默认选中省级tab
    })

    // const loading = ref() // 行政区骨架屏加载提示
    const buttonType = ref()
    const mouseTool = ref()
    const overlays = ref<overlaysType[]>([]) // 绘制多边形的数据
    const currenAreaPath = ref()
    const addAreaText = ref<Record<string, any>>()
    const addAreaPolygon = ref<Record<string, any>>()

    const polyCutMouseTool = ref() // 定义裁剪面的对象
    // const administrativePolygons = ref() // 定义行政区面的对象

    const polyEditorArr = ref<editType[]>([]) // 定义编辑面的对象数组

    const updatePolygon = ref()
    let num = 0
    let bool = false
    let text_: any
    const polygonEndArr: any = []
    let polygonEnd: any = {}
    let areaCountAll = 0
    const strokeColor_ = ''
    const strokeWeight_ = 1
    const fillColor_ = ''

    // 地图上实时更新颜色
    watch(
      () => [
        getStoreColorData.color.value.fillColor,
        getStoreColorData.color.value.strokeColor,
        getStoreColorData.color.value.strokeWeight
      ],
      () => {
        if (getStoreColorData.color.value) {
          let fillOpacity_ = 1
          let strokeOpacity_ = 1
          // 边框颜色
          if (
            getStoreColorData.color.value.strokeColor &&
            !getStoreColorData.color.value.strokeColor?.includes('#') &&
            getStoreColorData.color.value.strokeColor.length > 0
          ) {
            strokeOpacity_ = Number(
              getStoreColorData.color.value.strokeColor.split(',')[3].split(')')[0]
            )
          }
          // 填充颜色
          if (
            getStoreColorData.color.value.fillColor &&
            !getStoreColorData.color.value.strokeColor?.includes('#') &&
            getStoreColorData.color.value.fillColor.length > 0
          ) {
            fillOpacity_ = Number(
              getStoreColorData.color.value.fillColor.split(',')[3].split(')')[0]
            )
          }
          if (props.type === 'add') {
            if (addAreaPolygon.value) {
              addAreaPolygon.value.setOptions({
                strokeColor: getStoreColorData.color.value.strokeColor,
                strokeWeight: getStoreColorData.color.value.strokeWeight,
                fillColor: getStoreColorData.color.value.fillColor,
                fillOpacity: fillOpacity_,
                strokeOpacity: strokeOpacity_
              })
            }

            // 新增
            if (overlays.value.length > 0) {
              for (let k = 0; k < overlays.value.length; k++) {
                overlays.value[k].setOptions({
                  strokeColor: getStoreColorData.color.value.strokeColor,
                  strokeWeight: getStoreColorData.color.value.strokeWeight,
                  fillColor: getStoreColorData.color.value.fillColor,
                  fillOpacity: fillOpacity_,
                  strokeOpacity: strokeOpacity_
                })
              }
            }
            // 针对绘制了一个图形后修改了颜色， 再绘制第二个图形颜色保持一致
            if (
              mouseTool.value?.polygon &&
              getStoreColorData.color.value.fillColor &&
              getStoreColorData.color.value.strokeColor
            ) {
              mouseTool.value.polygon({
                fillColor: getStoreColorData.color.value.fillColor, // 默认面的填充色
                strokeColor: getStoreColorData.color.value.strokeColor, // 默认面的边线颜色
                strokeWeight: getStoreColorData.color.value.strokeWeight, // 线宽
                fillOpacity: Number(
                  getStoreColorData.color.value.fillColor.split(',')[3].split(')')[0]
                ),
                strokeOpacity: Number(
                  getStoreColorData.color.value.strokeColor.split(',')[3].split(')')[0]
                ),
                bubble: true
              })
            }
          } else {
            if (getStoreColorData.color.value.id) {
              for (let f = 0; f < props.overlaysArr.length; f++) {
                if (props.overlaysArr[f].id === getStoreColorData.color.value.id) {
                  for (let p = 0; p < props.overlaysArr[f].singlePolygon.length; p++) {
                    props.overlaysArr[f].singlePolygon[p].setOptions({
                      strokeColor: getStoreColorData.color.value.strokeColor,
                      strokeWeight: getStoreColorData.color.value.strokeWeight,
                      fillColor: getStoreColorData.color.value.fillColor,
                      fillOpacity: fillOpacity_,
                      strokeOpacity: strokeOpacity_
                    })
                  }
                }
              }
            }
          }
        }
      }
    )

    onMounted(async () => {
      bool = false

      if (props.record.id) {
        const editAreaPolygon = props.overlaysArr.find(
          (item: addOptionsPropsType['record']) => item?.id === props.record?.id
        )
        currenAreaPath.value = editAreaPolygon.polygon.getPath()
      }
      // if (!globalState?.provinceSelectList?.value?.length) {
      //   loading.value = true
      //   // 获取省市区下拉列表
      //   await store.dispatch('global/GetRegionSelectTreeList')
      //   loading.value = false
      // }
    })

    onBeforeUnmount(() => {
      if (state.disProvince) state.disProvince.setMap(null)
      if (text_) text_.remove()
      if (addAreaPolygon.value) {
        addAreaPolygon.value.destroy()
        addAreaText.value!.remove()
        // props.mapToolView.mapRef.remove(addAreaPolygon.value)
        // props.mapToolView.mapRef.remove(addAreaText.value)
      }
    })

    // 行政区 提示 按钮去掉高亮
    const domOnMouseleave = () => {
      buttonType.value = undefined
    }

    // 点击省级时替换市级列表并赋值
    const handleChangeActiveProvince = (item: ProvinceEnum) => {
      store.commit('global/SET_CITY_SELECT_LIST', item?.children || [])
      state.activeTabKey = 'city'
      state.activeProvince = item
      state.activeCity = undefined
      state.activeArea = undefined
    }

    // 点击市级时替换区级列表并赋值
    const handleChangeActiveCity = (item: CityEnum) => {
      store.commit('global/SET_AREA_SELECT_LIST', item?.children || [])
      state.activeTabKey = 'area'
      state.activeCity = item
      state.activeArea = undefined
    }

    // 点击区级时赋值
    const handleChangeActiveArea = (item: AreaEnum) => {
      state.activeArea = item
      new props.mapToolView.aMapRef.DistrictSearch({
        subdistrict: 0, // 获取边界不需要返回下级行政区
        extensions: 'all', // 返回行政区边界坐标组等具体信息
        level: 'district' // 查询行政级别为 省、市、区
      }).search(item.districtCode, (status: string, result: assetXzqDistrictListObj) => {
        state.disProvince && state.disProvince.setMap(null)
        state.disProvince = new props.mapToolView.aMapRef.DistrictLayer.Province({
          depth: 2,
          adcode: result.districtList[0].adcode,
          opacity: 0.5,
          styles: {
            fill: '#80d8ff',
            'county-stroke': '#0091ea'
          }
        })
        state.disProvince!.setMap(props.mapToolView.mapRef)
        const center = result.districtList[0].center
        props.mapToolView.mapRef.panTo([center?.lng, center?.lat], 30)
      })
    }

    // 递归过滤LngLat类型数据
    const handleFilterLngLatList = (
      arr: Record<string, any>[][] | Record<string, any>[] = []
    ): Position[][] => {
      const filterList = arr.map((item) =>
        isArray(item)
          ? handleFilterLngLatList(item as Record<string, any>[][])
          : (item as Record<string, any>)?.toArray()
      )
      if (
        !isArray(arr[0]) &&
        filterList?.length &&
        filterList[0].toString() !== filterList[filterList.length - 1].toString()
      ) {
        filterList.push(filterList[0])
      }
      return filterList
    }

    // 关闭工具条按钮
    const closeToolBtn = () => {
      num = 0
      bool = false

      // 编辑工具
      // let polyAllData = []
      if (polyEditorArr.value && polyEditorArr.value.length > 0) {
        polyEditorArr.value?.forEach((item) => {
          item.close(true)
          let editAreaPolygonPath, isMultiPolygon, editAreaPolygon
          if (props.record.id) {
            editAreaPolygon = props.overlaysArr.find(
              (findItem: addOptionsPropsType['record']) => findItem?.id === props.record?.id
            )
            if (!editAreaPolygon) return
            editAreaPolygonPath = handleFilterLngLatList(
              editAreaPolygon.polygon.getPath()
            ) as unknown as Position[][][]
            // 是否是多面
            isMultiPolygon = JSON.stringify(editAreaPolygonPath)?.includes('[[[[')
            editAreaPolygon.text!.setText(`面积：${areaCountAll}㎡`)
          } else {
            if (!addAreaPolygon.value) return
            editAreaPolygonPath = handleFilterLngLatList(
              addAreaPolygon.value!.getPath()
            ) as unknown as Position[][][]
            isMultiPolygon = JSON.stringify(editAreaPolygonPath)?.includes('[[[[')
            addAreaText.value!.setText(`面积：${areaCountAll}㎡`)
          }

          // 去遍历多面重新一个个合并一遍 防止编辑后因为重叠没有合并
          if (isMultiPolygon) {
            const multiPolygonPattern = editAreaPolygonPath?.reduce(
              (
                multiPolygonArr:
                  | Feature<Polygon | MultiPolygon, any>
                  | Feature<MultiPolygon, any>
                  | null,
                patternItem,
                index
              ) => {
                if (index === 0) return polygon(patternItem)
                return union(multiPolygonArr!, polygon(patternItem))
              },
              polygon([])
            )
            isMultiPolygon = multiPolygonPattern!.geometry.type === 'MultiPolygon'
            editAreaPolygonPath = multiPolygonPattern?.geometry?.coordinates as Position[][][]
            // 并更新面信息
            if (props.record.id) {
              editAreaPolygon.polygon.setPath(editAreaPolygonPath)
            } else {
              addAreaPolygon.value!.setPath(editAreaPolygonPath)
            }
          }

          areaCountAll = Math.round(
            Area(
              isMultiPolygon
                ? multiPolygon(editAreaPolygonPath)
                : polygon(editAreaPolygonPath as unknown as Position[][])
            )
          )
          if (props.record.id) {
            if (editAreaPolygon) {
              editAreaPolygon.text!.setText(`面积：${areaCountAll}㎡`)
            }
          } else {
            addAreaText.value!.setText(`面积：${areaCountAll}㎡`)
          }

          // 保存数据
          const dataP = {
            type: isMultiPolygon ? 'MultiPolygon' : 'Polygon',
            coordinates: editAreaPolygonPath
          }
          store.commit('assetWorkArea/SET_POLYGON_INFO', {
            id: props.record.id,
            polyArr: JSON.stringify(dataP),
            editCloseBool: !updatePolygon.value.editCloseBool,
            areaTotal: areaCountAll, // 面积
            type: 'editPolygon',
            polygonType: dataP.type,
            polygonPath: dataP.coordinates
          })
        })
      }

      // if (mouseTool.value) {
      //   mouseTool.value.close(true) // 关闭画图
      // }
      if (polyCutMouseTool.value) {
        polyCutMouseTool.value.close(true) // 关闭裁剪
      }

      if (text_) {
        text_.hide() // 隐藏文本提示
      }

      if (mouseTool.value) {
        mouseTool.value.close(true) // 关闭，并清除覆盖物
        // 如果新增面存在的话就显示
        if (addAreaPolygon.value) addAreaPolygon.value?.show?.()
        // 中间挖洞情况,保存数据
        if (polygonEndArr && polygonEndArr.length > 0) {
          const dataP = {
            type: getStoreData.polygonData.value.polygonType, // 几何类型
            coordinates: JSON.parse(getStoreData.polygonData.value.polyArr).coordinates // 几何数据
          }
          let type_ = ''
          if (props.record.id) {
            type_ = 'editPolygon'
          } else {
            type_ = 'addPolygon'
          }
          store.commit('assetWorkArea/SET_POLYGON_INFO', {
            id: props.record.id,
            polyArr: JSON.stringify(dataP),
            areaTotal: areaCountAll, // 面积
            type: type_,
            polygonType: dataP.type,
            polygonPath: dataP.coordinates
          })
        }

        if (polygonEnd.geometry) {
          let dataP
          let type_ = ''

          if (!props.record.id) {
            // 保存数据
            type_ = 'addPolygon'

            const simgleCoordinates = polygonEnd.geometry.coordinates
            areaCountAll = Math.round(Area(polygonEnd))

            dataP = {
              type: polygonEnd.geometry.type,
              coordinates: simgleCoordinates
            }
          } else {
            // 可能存在重新新增绘制的图形
            type_ = 'editPolygon'
            if (!getStoreData.polygonData.value.polyArr) {
              dataP = {
                type: polygonEnd.geometry.type,
                coordinates: polygonEnd.geometry.coordinates
              }
            } else {
              dataP = {
                type: polygonEnd.geometry.type,
                coordinates: JSON.parse(getStoreData.polygonData.value.polyArr).coordinates
              }
            }
          }
          store.commit('assetWorkArea/SET_POLYGON_INFO', {
            id: props.record.id,
            polyArr: JSON.stringify(dataP),
            areaTotal: areaCountAll, // 面积
            type: type_,
            polygonType: dataP.type,
            polygonPath: dataP.coordinates
          })
        }
      }
    }

    // 全屏按钮事件
    const fullScreen = () => {
      // closeToolBtn() // 关闭工具条按钮
      // buttonType.value = buttonType.value === 'fullScreen' ? undefined : 'fullScreen'
      props.changeFullScreen!()
    }

    // 绘图鼠标提示
    props.mapToolView.mapRef.on('mouseover', (e: { lnglat: { lng: number; lat: number } }) => {
      if (bool) {
        // 鼠标移入地图
        text_ = new props.mapToolView.aMapRef.Text({
          text: '单击以开始绘制',
          anchor: 'center', // 设置文本标记锚点
          draggable: false,
          offset: [0, -30],
          style: {
            'background-color': 'rgba(165, 42, 42, 0)',
            'border-width': 1,
            'text-align': 'center',
            'font-size': '14px',
            color: 'black'
          },
          position: [114.298572, 30.584355]
        })
        text_.setMap(props.mapToolView.mapRef)
        text_.show()
        text_.setPosition(e.lnglat)
        text_.setText('单击以开始绘制')
      }
    })

    props.mapToolView.mapRef.on('mouseout', () => {
      if (bool) {
        text_.hide()
      }
    })

    props.mapToolView.mapRef.on('click', (e: { lnglat: { lng: number; lat: number } }) => {
      if (bool) {
        text_.setPosition(e.lnglat)
        if (num > 1) {
          text_.setText('双击结束操作')
        } else {
          text_.setText('单击以继续绘制')
        }
        ++num
      }
    })

    props.mapToolView.mapRef.on('mousemove', (e: { lnglat: { lng: number; lat: number } }) => {
      if (bool) {
        text_.setPosition(e.lnglat)
        if (num > 0) {
          if (num > 1) {
            text_.setText('双击结束操作')
          } else {
            text_.setText('单击以继续绘制')
          }
        } else {
          text_.setText('单击以开始绘制')
        }
      }
    })

    // 地图双击事件
    props.mapToolView.mapRef.on('dblclick', function () {
      num = 0
    })

    // 行政区点击事件
    const handleFullScreenClick = () => {
      buttonType.value = buttonType.value === 'xzq' ? undefined : 'xzq'
    }

    // 画图按钮事件
    const drawPolygon = () => {
      num = 0
      bool = false
      closeToolBtn() // 关闭工具条按钮

      buttonType.value = buttonType.value === 'drawPolygon' ? undefined : 'drawPolygon'

      if (buttonType.value === 'drawPolygon') {
        mouseTool.value = new props.mapToolView.aMapRef.MouseTool(props.mapToolView.mapRef)
        bool = true

        // 地图工具绘制
        mouseTool.value.on('draw', function (e: { obj: overlaysType }) {
          // 重构面数据
          const path_ = e.obj.getPath()
          e?.obj?.hide?.()
          if (path_?.length <= 2) return
          overlays.value.push(e.obj) // 存放绘制的面
          // const arr = path_.map((item: Record<string, any>) => item?.toArray())
          const arr = handleFilterLngLatList(path_)

          // 编辑操作，则需要获取当时已经需要编辑的面数据,存在多个面的处理
          if (props.record.id) {
            const editAreaPolygon = props.overlaysArr.find(
              (item: addOptionsPropsType['record']) => item?.id === props.record?.id
            )
            if (editAreaPolygon) {
              const editAreaPolygonPath =
                (handleFilterLngLatList(
                  editAreaPolygon.polygon.getPath()
                ) as unknown as Position[][][]) || []
              // 是否是多面
              const isMultiPolygon = JSON.stringify(editAreaPolygonPath)?.includes('[[[[')
              polygonEnd = union(
                isMultiPolygon
                  ? multiPolygon(editAreaPolygonPath)
                  : polygon(editAreaPolygonPath as unknown as Position[][]),
                polygon([arr as unknown as Position[]])
              )
              areaCountAll = Math.round(Area(polygonEnd))
              editAreaPolygon.text!.setText(`面积：${areaCountAll}㎡`)
              editAreaPolygon.polygon.setPath(polygonEnd.geometry.coordinates)
              if (!editAreaPolygon.text.getPosition() && polygonEnd.geometry.coordinates.length) {
                editAreaPolygon.text.setPosition(
                  polygonEnd.geometry.type
                    ? props.getMapRandomPoint!(
                        polygonEnd.geometry.coordinates[0],
                        polygonEnd.geometry.coordinates
                      )
                    : props.getMapRandomPoint!(
                        polygonEnd.geometry.coordinates[0][0],
                        polygonEnd.geometry.coordinates[0]
                      )
                )
              }
            } else {
              polygonEnd = polygon([arr as unknown as Position[]])
              areaCountAll = props.mapToolView.aMapRef.GeometryUtil.ringArea(path_)
            }
            //
            const dataP = {
              type: polygonEnd.geometry.type,
              coordinates: polygonEnd.geometry.coordinates
            }
            store.commit('assetWorkArea/SET_POLYGON_INFO', {
              id: props.record.id,
              polyArr: JSON.stringify(dataP),
              areaTotal: areaCountAll, // 面积
              type: 'editPolygon',
              polygonType: dataP.type,
              polygonPath: dataP.coordinates
            })

            // 渲染高德面图形
            const polygonUnion = new props.mapToolView.aMapRef.Polygon({
              path: polygonEnd.geometry.coordinates,
              strokeColor: strokeColor_,
              strokeWeight: strokeWeight_,
              fillColor: fillColor_,
              zIndex: 2,
              bubble: true
            })

            polygonUnion.setPath(polygonEnd.geometry.coordinates)
            props.mapToolView.mapRef.add(polygonUnion)
          } else {
            // 新增
            if (arr?.length < 4) return
            // 针对新增操作,则是绘制多个面
            if (!addAreaPolygon.value) {
              addAreaPolygon.value = new props.mapToolView.aMapRef.Polygon({
                map: props.mapToolView.mapRef,
                path: arr,
                fillColor: getStoreColorData.color.value.fillColor,
                strokeColor: getStoreColorData.color.value.strokeColor,
                strokeWeight: getStoreColorData.color.value.strokeWeight,
                fillOpacity: Number(
                  getStoreColorData.color.value.fillColor.split(',')[3].split(')')[0]
                ),
                strokeOpacity: Number(
                  getStoreColorData.color.value.strokeColor.split(',')[3].split(')')[0]
                ),
                bubble: true
              })
              overlays.value = [addAreaPolygon.value!]
              polygonEnd = polygon([arr as unknown as Position[]])
              areaCountAll = Math.round(Area(polygonEnd))
              addAreaText.value = new props.mapToolView.aMapRef.Text({
                map: props.mapToolView.mapRef,
                // position: props.getMapRandomPoint!(
                //   arr[0] as unknown as number[],
                //   arr as unknown as number[]
                // ),
                position: new props.mapToolView.aMapRef.LngLat(
                  addAreaPolygon.value!.getBounds()?.getCenter().lng,
                  addAreaPolygon.value!.getBounds()?.getCenter().lat
                ),
                text: `面积：${areaCountAll}㎡`,
                anchor: 'center', // 设置文本标记锚点
                draggable: false,
                style: {
                  'background-color': 'rgba(165, 42, 42, 0)',
                  'border-width': 0,
                  'text-align': 'center',
                  'font-size': '14px',
                  color: 'black'
                },
                offset: new props.mapToolView.aMapRef.Pixel(-20, -20)
              })
            } else {
              // 隐藏鼠标工具中绘制好的面 并将新面整合进整个图形内
              // e?.obj?.hide?.()
              const editAreaPolygonPath = handleFilterLngLatList(
                addAreaPolygon.value.getPath()
              ) as unknown as Position[][][]
              const isMultiPolygon = JSON.stringify(editAreaPolygonPath)?.includes('[[[[')
              polygonEnd = union(
                isMultiPolygon
                  ? multiPolygon(editAreaPolygonPath)
                  : polygon([editAreaPolygonPath] as unknown as Position[][]),
                polygon([arr as unknown as Position[]])
              )
              areaCountAll = Math.round(Area(polygonEnd))
              addAreaText.value!.setText(`面积：${areaCountAll}㎡`)
              addAreaPolygon.value.setPath(
                polygonEnd.geometry.type === 'MultiPolygon'
                  ? polygonEnd.geometry.coordinates
                  : polygonEnd.geometry.coordinates[0]
              )
            }
          }
        })

        // 颜色渲染，判断是编辑操作还是新增操作, 新增时无record, 所以改用type判断
        if (props.type === 'update') {
          mouseTool.value.polygon({
            fillColor: props.record.backColor, // 面的填充色
            strokeColor: props.record.bordeColor, // 面的边线颜色
            strokeWeight: props.record.width, // 线宽
            fillOpacity: Number(props.record.backColor.split(',')[3].split(')')[0]),
            strokeOpacity: Number(props.record.bordeColor.split(',')[3].split(')')[0]),
            bubble: true
          })
        } else {
          if (getStoreColorData.color.value.fillColor) {
            mouseTool.value.polygon({
              fillColor: getStoreColorData.color.value.fillColor, // 默认面的填充色
              strokeColor: getStoreColorData.color.value.strokeColor, // 默认面的边线颜色
              strokeWeight: getStoreColorData.color.value.strokeWeight, // 线宽
              fillOpacity: Number(
                getStoreColorData.color.value.fillColor.split(',')[3].split(')')[0]
              ),
              strokeOpacity: Number(
                getStoreColorData.color.value.strokeColor.split(',')[3].split(')')[0]
              ),
              zIndex: 2,
              bubble: true
            })
          } else {
            mouseTool.value.polygon({
              fillColor: 'rgba(192, 219, 246, 1)', // 默认面的填充色
              strokeColor: 'rgba(7, 124, 254, 1)', // 默认面的边线颜色
              strokeWeight: 1, // 线宽
              fillOpacity: 1,
              strokeOpacity: 1,
              zIndex: 2,
              bubble: true
            })
          }
        }
      } else {
        closeToolBtn() // 关闭画图
      }
    }

    // 编辑按钮事件
    const editPolygon = () => {
      num = 0
      bool = false
      closeToolBtn()
      buttonType.value = buttonType.value === 'editPolygon' ? undefined : 'editPolygon'
      if (buttonType.value === 'editPolygon') {
        bool = true

        if (props.record.id) {
          const editAreaPolygon = props.overlaysArr.find(
            (item: addOptionsPropsType['record']) => item?.id === props.record?.id
          )
          if (!editAreaPolygon?.polygon?.getPath?.()) return
          const editBtn = new props.mapToolView.aMapRef.PolygonEditor(
            props.mapToolView.mapRef,
            editAreaPolygon?.polygon
          )
          editBtn.open()
          polyEditorArr.value.push(editBtn)

          updatePolygon.value = {
            polygonInfo: [editAreaPolygon?.polygon],
            editCloseBool: false,
            textArr: editAreaPolygon?.textArr
          }
        } else {
          if (!addAreaPolygon.value) return
          const editBtn = new props.mapToolView.aMapRef.PolygonEditor(
            props.mapToolView.mapRef,
            addAreaPolygon.value
          )
          editBtn.open()
          polyEditorArr.value.push(editBtn)
          updatePolygon.value = {
            polygonInfo: [addAreaPolygon.value],
            editCloseBool: false,
            textArr: [addAreaText.value]
          }
        }

        bool = false
        if (text_) {
          text_.hide() // 隐藏文本提示
        }
      } else {
        closeToolBtn() // 关闭画图
      }
    }

    // 裁剪按钮事件
    /* const cuttingPolygon = () => {
      num = 0
      bool = false
      let cropPoygon: any
      const lnglat_: any = []
      closeToolBtn()
      const needDigPolygon: any = []
      buttonType.value = buttonType.value === 'cuttingPolygon' ? undefined : 'cuttingPolygon'
      if (buttonType.value === 'cuttingPolygon') {
        bool = true
        mouseTool.value = new props.mapToolView.aMapRef.MouseTool(props.mapToolView.mapRef)

        // 开始绘制
        mouseTool.value.on('draw', function (e: { obj: overlaysType }) {
          overlays.value.push(e.obj)
          // areaCountAll = 0

          // 获取绘制的面数据
          const path_ = e.obj.getPath()
          const arr = []
          if (path_.length > 0) {
            for (let p = 0; p < path_.length; p++) {
              arr.push([path_[p].lng, path_[p].lat])
            }
          }

          // 定义绘制的turf的面对象
          const drawPolygon = arr
          drawPolygon.push(arr[0])
          const poly2 = polygon([drawPolygon], { fill: '#0f0' })

          // 需要被裁剪的面
          if (props.record.id) {
            if (cropPoygon) {
              // 根据单面和多面单判断，对数组重新组装数据
              needDigPolygon.splice(0, needDigPolygon.length) // 清空数组
              const path_ = cropPoygon.getPath()

              const singlePolyArr = [] // 单面的对象数组变量
              const multiplyPolyArr = [] // 多面的对象数组变量
              for (let p = 0; p < path_.length; p++) {
                const digsPoly = [] // 获取多面的数据变量
                const child_ = cropPoygon.getPath()[p]
                const childArr = []
                for (let y = 0; y < child_.length; y++) {
                  const digArr = []
                  if (cropPoygon.length > 1) {
                    // 多面
                    for (let r = 0; r < child_[y].length; r++) {
                      digArr.push([child_[y][r].lng, child_[y][r].lat])
                    }
                  } else {
                    // 单面
                    if (child_[y].length > 0) {
                      // 将单面裁剪成多个面
                      for (let d = 0; d < child_[y].length; d++) {
                        digArr.push([child_[y][d].lng, child_[y][d].lat])
                      }
                      digsPoly.push(digArr)
                    } else {
                      // 依旧是单面
                      childArr.push([child_[y].lng, child_[y].lat])
                    }
                  }
                }
                if (digsPoly.length > 0) {
                  multiplyPolyArr.push(digsPoly)
                }
                if (childArr.length > 0) {
                  singlePolyArr.push(childArr)
                }
              }

              // 渲染成turf的面对象
              if (multiplyPolyArr.length > 0) {
                // 多面
                for (let m = 0; m < multiplyPolyArr.length; m++) {
                  const poly = polygon(multiplyPolyArr[m], { fill: '#0f0' })
                  needDigPolygon.push(poly)
                }
              }
              if (singlePolyArr.length > 0) {
                // 单面
                const poly = polygon(singlePolyArr, { fill: '#0f0' })
                needDigPolygon.push(poly)
              }
            } else {
              for (let g = 0; g < props.overlaysArr.length; g++) {
                if (props.overlaysArr[g].id === props.record.id) {
                  // 选中需要编辑的面信息
                  let singlePoly = []
                  const path_ = props.overlaysArr[g].polygon.getPath()
                  if (JSON.parse(props.record.phase).type === 'MultiPolygon') {
                    // 多面
                    for (let p = 0; p < path_.length; p++) {
                      singlePoly = []
                      if (path_[p][0] && path_[p][0].length > 2) {
                        // 有洞
                        for (let g = 0; g < path_[p].length; g++) {
                          const childPoly = []
                          for (let w = 0; w < path_[p][g].length; w++) {
                            childPoly.push([path_[p][g][w].lng, path_[p][g][w].lat])
                          }
                          singlePoly.push(childPoly)
                        }
                        const poly = polygon(singlePoly, { fill: '#0f0' })
                        needDigPolygon.push(poly)
                      } else {
                        // 没有洞
                        for (let w = 0; w < path_[p].length; w++) {
                          singlePoly.push([path_[p][w].lng, path_[p][w].lat])
                        }
                        const poly = polygon([singlePoly], { fill: '#0f0' })
                        needDigPolygon.push(poly)
                      }
                    }
                  } else {
                    // 单面
                    for (let p = 0; p < path_.length; p++) {
                      if (path_[p].length > 0) {
                        const childArr = []
                        for (let w = 0; w < path_[p].length; w++) {
                          childArr.push([path_[p][w].lng, path_[p][w].lat])
                        }
                        singlePoly.push(childArr)
                      } else {
                        singlePoly.push([path_[p].lng, path_[p].lat])
                      }
                    }
                    const poly = polygon(singlePoly, { fill: '#0f0' })
                    needDigPolygon.push(poly)
                  }
                  // }
                }
              }
            }
          }

          polygonEndArr = []
          if (polygonEnd.geometry) {
            polygonEnd = difference(polygonEnd, poly2) // 对几何面求差异之后的数据
            polygonEndArr.push(polygonEnd)
          } else {
            const differArr = []

            if (needDigPolygon.length > 0) {
              // 多面
              for (let r = 0; r < needDigPolygon.length; r++) {
                const differenceInfo = difference(needDigPolygon[r], poly2)
                if (differenceInfo) {
                  differArr.push(differenceInfo)
                }
              }
              polygonEndArr = differArr
            }
          }

          // 计算面积
          if (polygonEndArr.length > 0) {
            let areaS = 0
            let multArea = 0
            if (polygonEndArr.length > 1 || polygonEndArr[0].geometry.type === 'MultiPolygon') {
              // 多面
              for (let p = 0; p < polygonEndArr.length; p++) {
                if (polygonEndArr[p].geometry.coordinates.length > 1) {
                  const polyLen = polygonEndArr[p].geometry.coordinates
                  let area1 = 0
                  for (let e = 0; e < polyLen.length; e++) {
                    if (polyLen[e].length > 1) {
                      if (polyLen[e].length > 1) {
                        // 多面 有洞
                        area1 = Math.round(
                          props.mapToolView.aMapRef.GeometryUtil.ringArea(polyLen[e][0]) // 面积
                        )
                        for (let k = 0; k < polyLen[e].length; k++) {
                          // 带洞
                          if (k > 0) {
                            const area2 = Math.round(
                              props.mapToolView.aMapRef.GeometryUtil.ringArea(polyLen[e][k]) // 面积
                            )
                            area1 = area1 - area2
                          }
                        }
                      } else {
                        // 没洞
                        const area3 = Math.round(
                          props.mapToolView.aMapRef.GeometryUtil.ringArea(polyLen[e][0]) // 面积
                        )
                        area1 = area1 + area3
                      }
                    }
                  }
                  multArea = multArea + area1
                } else {
                  // 单面
                  const areaNo = Math.round(
                    props.mapToolView.aMapRef.GeometryUtil.ringArea(
                      polygonEndArr[p].geometry.coordinates[0]
                    ) // 面积
                  )
                  multArea = multArea + areaNo
                }
              }
              areaCountAll = multArea
            } else {
              // 单面
              const coor_ = polygonEndArr[0].geometry.coordinates
              if (coor_.length > 1) {
                // 带洞
                const firstArea = Math.round(
                  props.mapToolView.aMapRef.GeometryUtil.ringArea(coor_[0]) // 面积
                )
                let allArea = 0
                for (let f = 0; f < coor_.length; f++) {
                  if (f > 0) {
                    const otherArea = Math.round(
                      props.mapToolView.aMapRef.GeometryUtil.ringArea(coor_[f]) // 面积
                    )
                    allArea = allArea + otherArea
                  }
                }
                areaS = firstArea - allArea
              } else {
                // 不带洞
                const areaNo = Math.round(
                  props.mapToolView.aMapRef.GeometryUtil.ringArea(coor_[0]) // 面积
                )
                areaS = areaS + areaNo
              }
              areaCountAll = areaS
            }
          } else {
            areaCountAll = 0
          }
          const simgleCoordinates = []

          // 组装数据格式
          if (polygonEndArr && polygonEndArr.length > 0) {
            if (polygonEndArr.length > 1) {
              // 多面
              for (let f = 0; f < polygonEndArr.length; f++) {
                const multiLen = polygonEndArr[f].geometry.coordinates
                if (multiLen.length > 1) {
                  // 多面 挖洞
                  const childMultiplyArr = []
                  for (let u = 0; u < multiLen.length; u++) {
                    if (polygonEndArr[f].geometry.type === 'MultiPolygon') {
                      simgleCoordinates.push(multiLen[u])
                    } else {
                      childMultiplyArr.push(multiLen[u])
                    }
                  }
                  if (childMultiplyArr.length > 0) {
                    simgleCoordinates.push(childMultiplyArr)
                  }
                } else {
                  // 没有挖洞
                  for (let u = 0; u < polygonEndArr[f].geometry.coordinates.length; u++) {
                    simgleCoordinates.push([polygonEndArr[f].geometry.coordinates[u]]) // 空间数据
                  }
                }
              }
            } else {
              // 单面
              if (polygonEndArr[0].geometry.coordinates.length > 1) {
                // 挖洞
                const arr_ = []
                const len_ = polygonEndArr[0].geometry.coordinates
                for (let w = 0; w < len_.length; w++) {
                  arr_.push(len_[w])
                }
                simgleCoordinates.push(arr_)
              } else {
                // 不带洞
                simgleCoordinates.push(polygonEndArr[0].geometry.coordinates[0]) // 空间数据
              }
            }
          }
          let dataP
          if (simgleCoordinates.length > 0) {
            if (simgleCoordinates.length > 1) {
              dataP = {
                type: 'MultiPolygon',
                coordinates: simgleCoordinates
              }
            } else {
              if (simgleCoordinates[0][0].length > 2) {
                dataP = {
                  type: 'Polygon',
                  coordinates: simgleCoordinates[0]
                }
              } else {
                dataP = {
                  type: 'Polygon',
                  coordinates: simgleCoordinates
                }
              }
            }
          } else {
            dataP = {} // 面对象完全不存在的情况
          }

          // 临时裁剪的几何图形是否存在
          if (cropPoygon) {
            cropPoygon.setMap(null)
            props.mapToolView.mapRef.remove(cropPoygon)
            lnglat_[0] = cropPoygon.getBounds()?.getCenter().lng // 中心点
            lnglat_[1] = cropPoygon.getBounds()?.getCenter().lat
            for (let g = 0; g < props.overlaysArr.length; g++) {
              if (props.overlaysArr[g].id === props.record.id) {
                for (let y = 0; y < props.overlaysArr[g].singlePolygon.length; y++) {
                  props.overlaysArr[g].text.setText(`${areaCountAll}㎡`) // 面积回显
                }
              }
            }
          } else {
            lnglat_[0] = e.obj.getBounds()?.getCenter().lng
            lnglat_[1] = e.obj.getBounds()?.getCenter().lat
            for (let g = 0; g < props.overlaysArr.length; g++) {
              if (props.overlaysArr[g].id === props.record.id) {
                for (let y = 0; y < props.overlaysArr[g].singlePolygon.length; y++) {
                  props.overlaysArr[g].text.setText(`${areaCountAll}㎡`) // 面积回显
                  props.overlaysArr[g].singlePolygon[y].setMap(null) // 移除已经存在的面数据
                }
              }
            }
          }

          cropPoygon = ''
          cropPoygon = new props.mapToolView.aMapRef.Polygon({
            path: simgleCoordinates,
            strokeColor: props.record.bordeColor,
            strokeWeight: props.record.width,
            fillColor: props.record.backColor,
            zIndex: 1,
            fillOpacity: Number(props.record.backColor.split(',')[3].split(')')[0]),
            strokeOpacity: Number(props.record.bordeColor.split(',')[3].split(')')[0])
          })
          cropPoygon.setPath(simgleCoordinates)
          props.mapToolView.mapRef.add(cropPoygon)

          e.obj.setMap(null)

          let type_ = ''
          if (props.record.id) {
            type_ = 'editPolygon'
          } else {
            type_ = 'addPolygon'
          }
          store.commit('assetWorkArea/SET_POLYGON_INFO', {
            id: props.record.id,
            polyArr: JSON.stringify(dataP),
            areaTotal: areaCountAll, // 面积
            type: type_,
            polygonType: dataP.type
          })
        })

        // 颜色设置
        mouseTool.value.polygon({
          fillColor: props.record.backColor, // 面的填充色
          strokeColor: props.record.bordeColor, // 面的边线颜色
          strokeWeight: props.record.width, // 线宽
          fillOpacity: Number(props.record.backColor.split(',')[3].split(')')[0]),
          strokeOpacity: Number(props.record.bordeColor.split(',')[3].split(')')[0])
        })
      } else {
        closeToolBtn() // 关闭画图
      }
    } */

    // 使用说明点击事件
    const handleHelpClick = () => {
      buttonType.value = buttonType.value === 'help' ? undefined : 'help'
    }

    // 修边按钮事件
    // const trimmingPolygon = () => {
    //   closeToolBtn() // 关闭工具条按钮
    //   num = 0
    //   bool = false
    //   buttonType.value = buttonType.value === 'trimmingPolygon' ? undefined : 'trimmingPolygon'
    // }
    // 撤销
    // const revoke = () => {
    //   closeToolBtn() // 关闭工具条按钮
    //   num = 0
    //   bool = false
    //   buttonType.value = buttonType.value === 'revoke' ? undefined : 'revoke'
    // }

    // // 恢复
    // const recovery = () => {
    //   closeToolBtn() // 关闭工具条按钮
    //   num = 0
    //   bool = false
    //   buttonType.value = buttonType.value === 'recovery' ? undefined : 'recovery'
    // }

    expose({ closeToolBtn, buttonType })

    return () => (
      <ElSpace class={styles['area-map-toolbar']} size={16} spacer="|">
        <ElTooltip placement="bottom" content="全屏">
          <ElButton
            text
            plain
            type={props.activeFullScreen ? 'primary' : 'info'}
            onClick={() => fullScreen()}
          >
            <AliIcon type="icon-quyuguanli-quanfu" />
          </ElButton>
        </ElTooltip>
        <ElPopover
          width={380}
          trigger="click"
          teleported={false}
          // {...{ onHide: domOnMouseleave }}
          v-slots={{
            reference: () => (
              <ElButton
                text
                plain
                type={buttonType.value === 'xzq' ? 'primary' : 'info'}
                onClick={handleFullScreenClick}
              >
                <ElTooltip effect="light" content="行政区" teleported={false}>
                  <AliIcon type="icon-quyuguanli-tubiao2" />
                </ElTooltip>
              </ElButton>
            )
          }}
        >
          <ElTabs v-model={state.activeTabKey}>
            <ElTabPane label="省级" name="province">
              <ElSkeleton
                animated
                rows={5}
                loading={!globalState?.provinceSelectList?.value?.length}
              />
              <ElSpace wrap>
                {globalState?.provinceSelectList?.value?.map((item: ProvinceEnum) => (
                  <ElLink
                    underline={false}
                    key={item?.id}
                    type={state.activeProvince?.id === item?.id ? 'primary' : undefined}
                    onClick={() => handleChangeActiveProvince(item)}
                  >
                    {item?.provinceName}
                  </ElLink>
                ))}
              </ElSpace>
            </ElTabPane>
            <ElTabPane
              label="市级"
              name="city"
              disabled={!globalState?.citySelectList?.value?.length}
            >
              <ElSpace wrap>
                {globalState?.citySelectList?.value?.map((item: CityEnum) => (
                  <ElLink
                    underline={false}
                    key={item?.id}
                    type={state.activeCity?.id === item?.id ? 'primary' : undefined}
                    onClick={() => handleChangeActiveCity(item)}
                  >
                    {item?.cityName}
                  </ElLink>
                ))}
              </ElSpace>
            </ElTabPane>
            <ElTabPane
              label="区级"
              name="area"
              disabled={!globalState?.areaSelectList?.value?.length}
            >
              <ElSpace wrap>
                {globalState?.areaSelectList?.value?.map((item: AreaEnum) => (
                  <ElLink
                    underline={false}
                    key={item?.id}
                    type={state.activeArea?.id === item?.id ? 'primary' : undefined}
                    onClick={() => handleChangeActiveArea(item)}
                  >
                    {item?.districtName}
                  </ElLink>
                ))}
              </ElSpace>
            </ElTabPane>
          </ElTabs>
        </ElPopover>
        <ElTooltip placement="bottom" content="画图">
          <ElButton
            text
            plain
            onClick={() => drawPolygon()}
            type={buttonType.value === 'drawPolygon' ? 'primary' : 'info'}
          >
            <AliIcon type="icon-quyuguanli-tubiao3" />
          </ElButton>
        </ElTooltip>
        <ElTooltip placement="bottom" content="编辑图形">
          <ElButton
            text
            plain
            onClick={() => editPolygon()}
            type={buttonType.value === 'editPolygon' ? 'primary' : 'info'}
          >
            <AliIcon type="icon-quyuguanli-tubiao4" />
          </ElButton>
        </ElTooltip>
        {/* <ElTooltip placement="bottom" content="裁剪">
          <ElButton
            text
            plain
            onClick={() => cuttingPolygon()}
            type={buttonType.value === 'cuttingPolygon' ? 'primary' : 'info'}
          >
            <AliIcon type="icon-quyuguanli-tubiao5" />
          </ElButton>
        </ElTooltip> */}
        <ElPopover
          width={300}
          trigger="click"
          teleported={false}
          {...{ onHide: domOnMouseleave }}
          v-slots={{
            reference: () => (
              <ElButton
                text
                plain
                type={buttonType.value === 'help' ? 'primary' : 'info'}
                onClick={handleHelpClick}
              >
                <ElTooltip effect="light" content="使用说明" teleported={false}>
                  <AliIcon type="icon-quyuguanli-tubiao10" />
                </ElTooltip>
              </ElButton>
            )
          }}
        >
          <ElDescriptions column={1}>
            <ElDescriptionsItem label="工具栏使用说明" />
            <ElDescriptionsItem label="全屏">缩放地图以展示当前城市全部视野。</ElDescriptionsItem>
            <ElDescriptionsItem label="行政区">
              选择行政区域，系统自动画图，可在行政区域图形的基础上做二次编辑。
            </ElDescriptionsItem>
            <ElDescriptionsItem label="画图">在原图形的基础上添加图形。</ElDescriptionsItem>
            <ElDescriptionsItem label="编辑图形">
              可拖拽图形边框点来调整图形大小，或者鼠标右键边框点进行点的删除。
            </ElDescriptionsItem>
            <ElDescriptionsItem label="裁剪">裁剪掉指定区域内的图形。</ElDescriptionsItem>
            <ElDescriptionsItem label="修边">
              剪切多个图形的重复区域，将多个图形合并为一个图形。
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElPopover>
      </ElSpace>
    )
  }
})
